package com.example.musicaiap.ui.player

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack // Use AutoMirrored version
import androidx.compose.material.icons.automirrored.filled.QueueMusic // Use AutoMirrored version
import androidx.compose.material.icons.filled.* // Keep other icons
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.foundation.layout.WindowInsets // Import WindowInsets
import androidx.compose.foundation.layout.navigationBars // Import navigationBars
import androidx.compose.foundation.layout.statusBars // Import statusBars
import androidx.compose.ui.draw.blur // Import blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.musicaiap.R // Import R for placeholder
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.ui.player.PlayerContract.PlayerIntent
import com.example.musicaiap.ui.player.PlayerContract.PlayerEffect
import com.example.musicaiap.ui.player.PlayerContract.PlayMode
import com.example.musicaiap.ui.theme.MusicAIAPTheme
import java.util.concurrent.TimeUnit

/**
 * 全屏播放界面 (重构版)
 */
@Composable
fun PlayerScreen(
    onNavigateBack: () -> Unit,
    onNavigateToPlaylist: () -> Unit, // Keep for bottom playlist button (UI only for now)
    viewModel: PlayerViewModel = hiltViewModel()
) {
    val playerState by viewModel.uiState.collectAsState()

    // TODO: Handle effects if needed (e.g., show error snackbar)
    // LaunchedEffect(Unit) { ... }

    PlayerScreenContent(
        playerState = playerState,
        onNavigateBack = onNavigateBack,
        onPlayPause = { viewModel.processIntent(PlayerIntent.PlayPause) },
        onSkipPrevious = { viewModel.processIntent(PlayerIntent.SkipPrevious) },
        onSkipNext = { viewModel.processIntent(PlayerIntent.SkipNext) },
        onSeek = { positionMs -> viewModel.processIntent(PlayerIntent.SeekTo(positionMs)) },
        onToggleFavorite = { songId -> viewModel.processIntent(PlayerIntent.ToggleFavorite(songId)) },
        onMoreOptionsClick = { /* TODO: Implement More Options */ },
        onTogglePlayMode = { /* TODO: Implement Play Mode Toggle (UI only for now) */ },
        onPlaylistClick = { /* TODO: Implement Playlist Queue (UI only for now) */ }
    )
}

@Composable
private fun PlayerScreenContent(
    playerState: PlayerContract.PlayerState,
    onNavigateBack: () -> Unit,
    onPlayPause: () -> Unit,
    onSkipPrevious: () -> Unit,
    onSkipNext: () -> Unit,
    onSeek: (Long) -> Unit,
    onToggleFavorite: (String) -> Unit,
    onMoreOptionsClick: () -> Unit,
    onTogglePlayMode: () -> Unit,
    onPlaylistClick: () -> Unit
) {
    // Local state for slider interaction
    var sliderPosition by remember(playerState.currentSong?.id) { mutableStateOf(playerState.currentPosition.toFloat()) }
    var isSeeking by remember { mutableStateOf(false) }

    // Update slider position when not seeking and current position changes
    LaunchedEffect(playerState.currentPosition, isSeeking) {
        if (!isSeeking) {
            sliderPosition = playerState.currentPosition.toFloat()
        }
    }

    Box(modifier = Modifier.fillMaxSize()) { // Changed Column to Box

        // Background Layer (Blurred Image or Solid Color)
        if (!playerState.currentSong?.coverUrl.isNullOrEmpty()) {
            AsyncImage(
                model = ImageRequest.Builder(LocalContext.current)
                    .data(playerState.currentSong?.coverUrl)
                    .crossfade(true)
                    .build(),
                contentDescription = "背景封面",
                contentScale = ContentScale.Crop, // Crop to fill
                modifier = Modifier
                    .fillMaxSize()
                    .blur(radius = 25.dp) // Apply blur
            )
        } else {
            // Default solid background if no cover art
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(MaterialTheme.colorScheme.background)
            )
        }

        // Semi-transparent overlay for content readability
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background.copy(alpha = 0.2f)) // Reduced alpha for more visible blur
        )

         // Foreground Content Layer
         Column(
             modifier = Modifier
                 .fillMaxSize()
             // Removed .statusBarsPadding() and .navigationBarsPadding()
         ) {
             // Top Bar (Simplified: only back button)
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .windowInsetsPadding(WindowInsets.statusBars) // Add padding for status bar manually
                    .padding(horizontal = 4.dp, vertical = 8.dp) // Keep existing padding
            ) {
                IconButton(
                    onClick = onNavigateBack,
                    modifier = Modifier.align(Alignment.CenterStart)
                ) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "返回",
                        tint = MaterialTheme.colorScheme.onSurface // Adjust tint as needed
                    )
                }
                // Title removed as per the image design
            }

            // Main Content Area
            Column(
                modifier = Modifier
                    .weight(1f) // Takes up remaining space above bottom controls
                    .padding(horizontal = 32.dp), // Horizontal padding for content
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center // Center content vertically
            ) {
                // Polaroid Style Cover Art
                Card(
                    modifier = Modifier
                        .fillMaxWidth(0.85f) // Adjust width as needed
                        .aspectRatio(1f) // Maintain square aspect ratio for the card frame
                        .graphicsLayer {
                            // Optional: Add slight rotation for polaroid effect
                            // rotationZ = -2f
                        },
                    shape = RoundedCornerShape(4.dp), // Less rounded corners for polaroid
                    elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                    colors = CardDefaults.cardColors(containerColor = Color.White) // Polaroid frame color
                ) {
                    AsyncImage(
                        model = ImageRequest.Builder(LocalContext.current)
                            .data(playerState.currentSong?.coverUrl ?: R.drawable.ic_notification_music) // Use placeholder if null or empty (Coil handles empty string)
                            .error(R.drawable.ic_notification_music) // Error placeholder
                            .placeholder(R.drawable.ic_notification_music) // Loading placeholder
                            .crossfade(true)
                            .build(),
                        contentDescription = "歌曲封面",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp) // Padding inside the white frame for the image
                            .clip(RoundedCornerShape(2.dp)) // Slightly rounded image corners
                    )
                }

                Spacer(modifier = Modifier.height(32.dp)) // Space below cover

                // Song Info Row
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    // Song Title (takes available space)
                    Text(
                        text = playerState.currentSong?.title ?: "---",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onBackground,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f, fill = false) // Allow text to shrink if needed, but don't force fill
                            .padding(end = 8.dp) // Add padding before buttons
                    )

                    // Favorite Button
                    IconButton(
                        onClick = { playerState.currentSong?.id?.let { onToggleFavorite(it) } },
                        modifier = Modifier.size(36.dp) // Smaller icon button
                    ) {
                        Icon(
                            imageVector = if (playerState.isFavorite) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
                            contentDescription = if (playerState.isFavorite) "取消收藏" else "收藏",
                            tint = if (playerState.isFavorite) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.size(24.dp) // Icon size
                        )
                    }

                    // More Options Button
                    IconButton(
                        onClick = onMoreOptionsClick,
                        modifier = Modifier.size(36.dp) // Smaller icon button
                    ) {
                        Icon(
                            imageVector = Icons.Filled.MoreVert,
                            contentDescription = "更多选项",
                            tint = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.size(24.dp) // Icon size
                        )
                    }
                }

                Spacer(modifier = Modifier.height(16.dp)) // Space below title row

                // Progress Slider and Time
                Column(modifier = Modifier.fillMaxWidth()) {
                    Slider(
                        value = sliderPosition,
                        onValueChange = { newValue ->
                            isSeeking = true
                            sliderPosition = newValue
                        },
                        valueRange = 0f..(playerState.duration.toFloat().coerceAtLeast(1f)), // Ensure range is at least 0..1 to avoid crash
                        onValueChangeFinished = {
                            onSeek(sliderPosition.toLong())
                            isSeeking = false
                        },
                        modifier = Modifier.fillMaxWidth(),
                        colors = SliderDefaults.colors(
                            thumbColor = MaterialTheme.colorScheme.primary,
                            activeTrackColor = MaterialTheme.colorScheme.primary,
                            inactiveTrackColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.1f)
                        )
                    )
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 8.dp), // Padding for time text
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        // Show slider position while seeking, otherwise show current position
                        Text(
                            text = formatDuration(if (isSeeking) sliderPosition.toLong() else playerState.currentPosition),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = formatDuration(playerState.duration),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                Spacer(modifier = Modifier.height(24.dp)) // Space below progress

                // Playback Controls
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onSkipPrevious, modifier = Modifier.size(48.dp)) {
                        Icon(
                            imageVector = Icons.Default.SkipPrevious,
                            contentDescription = "上一首",
                            tint = MaterialTheme.colorScheme.onSurface, // Use onSurface for controls
                            modifier = Modifier.size(36.dp)
                        )
                    }
                    IconButton(
                        onClick = onPlayPause,
                        modifier = Modifier
                            .size(72.dp) // Larger play/pause button
                            .background(MaterialTheme.colorScheme.primary, CircleShape)
                    ) {
                        Icon(
                            imageVector = if (playerState.isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow,
                            contentDescription = if (playerState.isPlaying) "暂停" else "播放",
                            tint = MaterialTheme.colorScheme.onPrimary, // White icon on primary background
                            modifier = Modifier.size(48.dp)
                        )
                    }
                    IconButton(onClick = onSkipNext, modifier = Modifier.size(48.dp)) {
                        Icon(
                            imageVector = Icons.Default.SkipNext,
                            contentDescription = "下一首",
                            tint = MaterialTheme.colorScheme.onSurface, // Use onSurface for controls
                            modifier = Modifier.size(36.dp)
                        )
                    }
                }

                Spacer(modifier = Modifier.height(32.dp)) // Space above bottom controls
            }

            // Bottom Controls (UI Only for now)
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .windowInsetsPadding(WindowInsets.navigationBars) // Add padding for navigation bar manually
                    .padding(horizontal = 32.dp, vertical = 16.dp), // Keep existing padding
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Play Mode Button (Placeholder)
                IconButton(onClick = onTogglePlayMode, modifier = Modifier.size(48.dp)) {
                    // TODO: Use correct icon based on actual playMode state later
                    Icon(
                        imageVector = Icons.Filled.Repeat, // Placeholder icon
                        contentDescription = "播放模式",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(24.dp)
                    )
                }

                // Playlist Button (Placeholder)
                IconButton(onClick = onPlaylistClick, modifier = Modifier.size(48.dp)) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.QueueMusic,
                        contentDescription = "播放列表",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
    }
}

// Helper function to format milliseconds to mm:ss string
private fun formatDuration(ms: Long): String {
    val minutes = TimeUnit.MILLISECONDS.toMinutes(ms)
    val seconds = TimeUnit.MILLISECONDS.toSeconds(ms) % 60
    return String.format("%02d:%02d", minutes, seconds)
}


@Preview(showBackground = true)
@Composable
fun PlayerScreenContentPreview() {
    val sampleSong = Song(
        id = "1",
        title = "1989 (Taylor's Version) [Deluxe]",
        artist = "Taylor Swift",
        album = "1989",
        url = "",
        coverUrl = "https://via.placeholder.com/300", // Placeholder cover
        duration = 245000L // Example duration
    )
    val state = PlayerContract.PlayerState(
        currentSong = sampleSong,
        isPlaying = false,
        currentPosition = 65000L, // Example position
        duration = 245000L,
        isFavorite = true,
        playMode = PlayMode.SEQUENCE
    )
    MusicAIAPTheme {
        PlayerScreenContent(
            playerState = state,
            onNavigateBack = {},
            onPlayPause = {},
            onSkipPrevious = {},
            onSkipNext = {},
            onSeek = {},
            onToggleFavorite = {},
            onMoreOptionsClick = {},
            onTogglePlayMode = {},
            onPlaylistClick = {}
        )
    }
}

@Preview(showBackground = true, device = "spec:width=360dp,height=640dp,dpi=480")
@Composable
fun PlayerScreenContentPlayingPreview() {
    val sampleSong = Song(
        id = "1",
        title = "Track 16",
        artist = "Unknown Artist",
        album = "Unknown Album",
        url = "",
        coverUrl = "", // Use empty string instead of null for preview test
        duration = 180000L
    )
    val state = PlayerContract.PlayerState(
        currentSong = sampleSong,
        isPlaying = true,
        currentPosition = 90000L,
        duration = 180000L,
        isFavorite = false,
        playMode = PlayMode.SHUFFLE
    )
    MusicAIAPTheme {
        PlayerScreenContent(
            playerState = state,
            onNavigateBack = {},
            onPlayPause = {},
            onSkipPrevious = {},
            onSkipNext = {},
            onSeek = {},
            onToggleFavorite = {},
            onMoreOptionsClick = {},
            onTogglePlayMode = {},
            onPlaylistClick = {}
        )
    }
}
